package desi.bakar.coreservice;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;

import java.io.IOException;

import static java.beans.Beans.isInstanceOf;


public class ValueObjectRawDataPopulater extends DeserializationProblemHandler {
    @Override
    public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jp, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException, JsonProcessingException {
        if (isInstanceOf(beanOrClass, SupportsRawData.class)) {
            RawField<?> rawField = discoverField(beanOrClass, propertyName);
            if (rawField != null) {
                Object value = jp.readValueAs(rawField.typeName());
                SupportsRawData.class.cast(beanOrClass).putRawData((RawField<Object>) rawField, value);
            }
            return true;
        } else {
            return super.handleUnknownProperty(ctxt, jp, deserializer, beanOrClass, propertyName);
        }
    }

    private RawField<?> discoverField(Object bean, String propertyName) {
        //TODO determine this dynamically
        return StringField.lastName;
    }
}
